#include "kernel_operator.h"
#include <cstdint>

constexpr int32_t TOTAL_LENGTH = 8 * 2048;
constexpr int32_t USE_CORE_NUM = 8;
constexpr int32_t BLOCK_LENGTH = TOTAL_LENGTH / USE_CORE_NUM; 
constexpr int32_t TILE_NUM = 8;
constexpr int32_t BUFFER_NUM = 2;
constexpr int32_t TILE_LENGTH = BLOCK_LENGTH / TILE_NUM / BUFFER_NUM;

__aicore__ inline bool IsFloat32NaN(float val) {
    return (*reinterpret_cast<const uint32_t*>(&val) == 0x7FC00000);
}

class KernelIsnan {
public:
    __aicore__ inline KernelIsnan() {}

    __aicore__ inline void Init(GM_ADDR x, GM_ADDR out) {
        int32_t blockIdx = AscendC::GetBlockIdx();
        xGm.SetGlobalBuffer((__gm__ float*)x + blockIdx * BLOCK_LENGTH, BLOCK_LENGTH);
        outGm.SetGlobalBuffer((__gm__ bool*)out + blockIdx * BLOCK_LENGTH, BLOCK_LENGTH);

        pipe.InitBuffer(inQueueX, BUFFER_NUM, TILE_LENGTH * sizeof(float));
        pipe.InitBuffer(outQueueBool, BUFFER_NUM, TILE_LENGTH * sizeof(bool));
    }

    __aicore__ inline void Process() {
        int32_t loopCount = TILE_NUM * BUFFER_NUM;
        for (int32_t i = 0; i < loopCount; i++) {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
    }

private:
    __aicore__ inline void CopyIn(int32_t progress) {
        AscendC::LocalTensor<float> xLocal = inQueueX.AllocTensor<float>();
        
        AscendC::DataCopy(xLocal, xGm[progress * TILE_LENGTH], TILE_LENGTH);
        inQueueX.EnQue(xLocal);
    }

    __aicore__ inline void Compute(int32_t progress) {
        AscendC::LocalTensor<float> xLocal = inQueueX.DeQue<float>();
        AscendC::LocalTensor<bool> outLocal = outQueueBool.AllocTensor<bool>();

        for (int32_t i = 0; i < TILE_LENGTH; i++) {
            float element = xLocal.GetValue(i);
            outLocal.SetValue(i, IsFloat32NaN(element)); //判断是否为NaN
        }

        outQueueBool.EnQue(outLocal);  // 输出入队
        inQueueX.FreeTensor(xLocal);   // 释放输入 UB
    }

    __aicore__ inline void CopyOut(int32_t progress) {
        AscendC::LocalTensor<bool> outLocal = outQueueBool.DeQue<bool>();

        AscendC::DataCopy(outGm[progress * TILE_LENGTH], outLocal, TILE_LENGTH);
        outQueueBool.FreeTensor(outLocal);
    }
    
private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueX;
    AscendC::TQue<AscendC::TPosition::VECOUT, BUFFER_NUM> outQueueBool;
    AscendC::GlobalTensor<float> xGm;
    AscendC::GlobalTensor<bool> outGm;
};

extern "C" __global__ __aicore__ void isnan_custom(GM_ADDR x, GM_ADDR out)
{
    KernelIsnan op;
    op.Init(x, out);
    op.Process();
}

#ifndef ASCENDC_CPU_DEBUG
void isnan_custom_do(uint32_t blockDim, void *stream, void *x, void *out)
{
    isnan_custom<<<blockDim, nullptr, stream>>>(x, out);
}
#endif